<template>
  <div class="base-map-resource-content">
    <div class="query-content">
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline backend-form"
      >
        <el-form-item label="用户名称">
          <el-input v-model="formInline.userName" @change="onSubmit" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="formInline.userPhone" @change="onSubmit" />
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select
            v-model="formInline.roleId"
            placeholder="请选择"
            @change="onSubmit"
            clearable
          >
            <el-option
              v-for="(item, index) in userRoleDict"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            @change="onSubmit"
            v-model="formInline.userState"
            placeholder="请选择"
            clearable
          >
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="2" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-button type="primary" class="queryButton" @click="onSubmit"-->
        <!--            >查询</el-button-->
        <!--          >-->
        <!--          <el-button type="primary" class="resetButton" @click="resetField"-->
        <!--            >重置</el-button-->
        <!--          >-->
        <!--        </el-form-item>-->
        <el-form-item class="backend-button">
          <el-button class="addButton" type="primary" @click="handleAddUser" v-if="currentUser?.hasPermission('yhzzgladd')">
            <i class="el-icon el-icon-plus"></i>
            {{ currentUser?.getButtonName('yhzzgladd') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column align="center" label="序号" width="180">
          <template #default="scope">
            {{ scope.$index + 1 }}
            <!--              {{ scope.$index + 1 + formInline.pageSize * (formInline.pageIndex - 1) }}-->
          </template>
        </el-table-column>
        <el-table-column
          label="用户名"
          prop="loginName"
          show-overflow-tooltip
        />
        <el-table-column label="真实姓名" show-overflow-tooltip>
          <template #default="scope">
            <span class="userName">
              {{ scope.row.userName }}
              <!--                <el-icon v-if="scope.row.userState === 1" class="item">-->
              <!--                  <SvgIcon name="user-management"></SvgIcon>-->
              <!--                </el-icon>-->
              <!--                <el-badge value="-" class="item" v-else>-->
              <!--                  <el-icon>-->
              <!--                    <SvgIcon name="user-management"></SvgIcon>-->
              <!--                  </el-icon>-->
              <!--                </el-badge>-->
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="手机号码"
          prop="userPhone"
          show-overflow-tooltip
        />
        <el-table-column
          label="用户角色"
          prop="roleName"
          show-overflow-tooltip
        />
        <el-table-column
          prop="areaName"
          label="用户所属区域"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{
              scope.row.createTime
                ? formatDate(
                    new Date(scope.row.createTime),
                    'YYYY-MM-DD HH:mm:ss'
                  )
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column prop="userState" label="是否禁用">
          <template #default="scope">
            <el-popconfirm
              width="160px"
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon-color="#626AEF"
              @confirm="confirmEvent(scope.row.pkid, scope.row.userState)"
              :title="
                '确认' +
                getTextByStatus(scope.row.userState) +
                '用户' +
                scope.row.userName +
                '吗？'
              "
            >
              <template #reference>
                <el-switch
                  :value="scope.row.userState === 2"
                  @change="handleEditUser(scope.row)"
                />
              </template>
            </el-popconfirm>

            <!--              <span v-if="scope.row.userState === 1">启用</span>-->
            <!--              <span v-else style="color: #FF455F;">禁用</span>-->
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              text
              type="text"
              style="padding: 0"
              @click="handleEditUserOld(scope.row)"
              v-if="currentUser?.hasPermission('yhzzgledit')"
            >
            {{ currentUser?.getButtonName('yhzzgledit') }}
            </el-button>
            <el-button
              text
              type="text"
              style="padding: 0"
              @click="handleEditClick(scope.row)"
              v-if="currentUser?.hasPermission('yhzzglpassword')"
            >
            {{ currentUser?.getButtonName('yhzzglpassword') }}
            </el-button>
            <!--              <el-button text style="color: #28B1E4;padding: 0">-->
            <!--                移入黑名单-->
            <!--              </el-button>-->
            <!--              <el-button text style="color: #FA3434">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      background
      layout="slot,prev, pager, next"
      :page-size="formInline.pageSize"
      :current-page="formInline.pageIndex"
      :total="total"
      @current-change="handlePageChange"
    >
      <template #default> 共{{ total }}个用户 </template>
    </el-pagination>
    <change-password
      :userInfo="userInfo"
      :user-role-dict="userRoleDict"
      :visible="changeUserDialogVisible"
      @closeDialog="handleChangePasswordDialogClose"
      @updateUser="handleChangePasswordUserUpdate"
    />
    <add-user-dialog
      :userInfo="userInfo"
      :visible="dialogVisible"
      :userRoleDict="userRoleDict"
      @updateUser="handleUserUpdate"
      @closeDialog="handleDialogClose"
    />
    <!--    <el-dialog-->
    <!--      :visible.sync="blackAddDialogVisible"-->
    <!--      title="提示"-->
    <!--      align-center-->
    <!--      :append-to-body="true"-->
    <!--      class="outline-dialog"-->
    <!--      width="30%"-->
    <!--    >-->
    <!--      <span>-->
    <!--        {{-->
    <!--          `确认${getTextByStatus(userInfo.userState)}用户${-->
    <!--            userInfo.userName-->
    <!--          }吗？`-->
    <!--        }}</span-->
    <!--      >-->
    <!--      <template #footer>-->
    <!--        <div class="dialog-footer">-->
    <!--          <el-button @click="blackAddDialogVisible = false">取消</el-button>-->
    <!--          <el-button-->
    <!--            type="primary"-->
    <!--            @click="confirmEvent(userInfo.pkid, userInfo.userState)"-->
    <!--          >-->
    <!--            确认-->
    <!--          </el-button>-->
    <!--        </div>-->
    <!--      </template>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import { Message as ElMessage } from 'element-ui'
// import AddUserDialog from "@/views/backend-management/components/user/components/addUserDialog.vue";
import { queryUserList, updateUser } from '@/api/back-management/user'
import type {
  updateUserParams,
  UserInfoResponse,
  userQueryParams,
} from '@/api/back-management/user/interface'
import { formatDate } from '@/utils'
import type { roleQueryParams } from '@/api/back-management/role/interface'
import { queryRoleList } from '@/api/back-management/role'
import type { OptionData } from '@/utils/type'
import ChangePassword from '@/views/backend-management/components/user/components/changePassword.vue'
import cache from '@/utils/cache'
import AddUserDialog from '@/views/backend-management/components/user/components/addUserDialog.vue'
import { getCurrentInstance } from 'vue'

const vm = getCurrentInstance()
console.log('vm', vm)
const store = vm.proxy.$store

const currentUser = store.state.user.currentUser

const userRoleDict = ref<OptionData[]>([
  {
    label: '市级管理员',
    value: 'citymanager',
  },
  {
    label: '社区管理员',
    value: 'socialmanager',
  },
  {
    label: '街道管理员',
    value: 'streetmanager',
  },
  {
    label: '区建委',
    value: 'checkmanager',
  },
])

const changeUserDialogVisible = ref(false)
const blackAddDialogVisible = ref(false)

const dialogVisible = ref(false)

const formInline = reactive<userQueryParams>({
  pageIndex: 1,
  pageSize: 11,
  userName: '',
  roleId: '',
  userState: '',
  userPhone: '',
})
const tableData = ref<UserInfoResponse[]>([])
const total = ref(0)

const userInfo = reactive<updateUserParams>({})

const getUserList = () => {
  queryUserList(formInline).then((res) => {
    const { success, data } = res
    if (success) {
      const { count, list } = data
      tableData.value = list
      total.value = count
    }
  })
}

const getRoleList = () => {
  const params: roleQueryParams = {
    pageIndex: 1,
    pageSize: 999,
  }
  queryRoleList(params).then((res) => {
    if (res.success) {
      userRoleDict.value = []
      res.data.list.forEach((val) => {
        userRoleDict.value.push({
          label: val.roleName,
          value: val.pkid,
          level: val.roleLevel,
        })
      })
    }
  })
}

onMounted(() => {
  getUserList()
  getRoleList()
})

const onSubmit = () => {
  formInline.pageIndex = 1
  getUserList()
}

const resetField = () => {
  formInline.pageIndex = 1
  formInline.pageSize = 11
  formInline.userName = ''
  formInline.roleId = ''
  formInline.userPhone = ''
  formInline.userState = ''
  getUserList()
}

const handleEditClick = (item: updateUserParams) => {
  const user = JSON.parse(cache.getItem('user')!).user
  const roleId = user.roleId
  const roleLevel = user.roleLevel
  if (
    roleId === 'citymanager' ||
    roleLevel == '4' ||
    roleId === 'checkmanager'
  ) {
    Object.assign(userInfo, item)
    changeUserDialogVisible.value = true
  } else {
    ElMessage.error('用户无权限，请联系管理员进行修改！')
  }
  // console.log(item);
}

const handleEditUser = (item: updateUserParams) => {
  // console.log(item);
  Object.assign(userInfo, item)
  // blackAddDialogVisible.value = true
}

const handleAddUser = () => {
  Object.keys(userInfo).forEach((key) => {
    delete userInfo[key]
  })
  dialogVisible.value = true
}

const handleEditUserOld = (item: any) => {
  Object.assign(userInfo, item)
  dialogVisible.value = true
}

const handleUserUpdate = () => {
  dialogVisible.value = false
  onSubmit()
}

const handleDialogClose = () => {
  dialogVisible.value = false
}

const handleChangePasswordDialogClose = () => {
  changeUserDialogVisible.value = false
}

const handleChangePasswordUserUpdate = () => {
  changeUserDialogVisible.value = false
  onSubmit()
}

const handlePageChange = (pageIndex: number) => {
  formInline.pageIndex = pageIndex
  getUserList()
}

const getTextByStatus = (status?: 1 | 2) => {
  if (status === 1) {
    return '禁用'
  } else {
    return '启用'
  }
}

const confirmEvent = (pkid: string, status: 1 | 2) => {
  let params: updateUserParams
  if (status === 1) {
    params = {
      userState: 2,
    }
  } else {
    params = {
      userState: 1,
    }
  }
  updateUser(pkid, params).then((res) => {
    if (res.success) {
      getUserList()
      blackAddDialogVisible.value = false
      ElMessage.success('更新用户成功！')
    }
  })
}
</script>

<style lang="scss" scoped>
.base-map-resource-content {
  width: 100%;
  height: calc(100% - 27px);
  background-color: white;
  box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
  border-radius: 2px;
  display: flex;
  flex-direction: column;

  .query-content {
    padding-left: 20px;
    width: 100%;
    line-height: 62px;
    border-bottom: 1px solid #eeeff5;

    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 0;

        .resetButton {
          width: 80px;
          height: 32px;
          color: #28b1e4;
          background: #ffffff;
          border: 1px solid #28b1e4;
          border-radius: 2px;
        }

        .queryButton {
          width: 80px;
          height: 32px;
          background: #28b1e4;
          border-radius: 2px;
        }
      }
    }
  }

  .addButton {
    margin-left: 20px;
    margin-top: 14px;
    margin-bottom: 14px;
    width: 100px;
    min-height: 32px;
    //background: #28b1e4;
    border-radius: 2px;
    //border: none;
    padding: 0;
  }

  .table {
    width: 100%;
    padding: 0 18px;
    overflow-y: auto;

    .userName {
      .item {
        margin-left: 6px;
      }
      :deep(.el-icon) {
        vertical-align: sub;

        .svg-icon {
          svg {
            width: 16px;
            height: 16px;
            color: #28b1e4;
          }
        }
      }
      :deep(.el-badge__content) {
        width: 12px;
        height: 13px;
        transform: translateY(85%) translateX(148%);
      }
    }

    :deep(.el-table__row--striped) {
      background: #f7f9fb;
    }
  }

  .el-pagination {
    margin-top: 20px;
    justify-content: end;
    margin-right: 18px;
    margin-bottom: 20px;
  }
}
</style>
